
/**
 * from 3.1.0.beta已经废弃
 * @param $
 */
(function ($){
	charts = {
		initCharts:function($obj,data){
			var chartObj = null;
			if (data.contents && data.contents.length == 1) {
				// 单个内容
				chartObj = this.singleContent($obj, data);
			} else if (data.contents && data.contents.length > 1) {
				// 多个内容
				chartObj = this.moreContent($obj, data);
			}
			if (data.contents && data.contents.length > 0) 
				charts.genSelector($obj,data.contents[0].reportId,chartObj);
		},
		singleContent:function($obj, data) {
			var content = data.contents[0];
			var reportId = content.reportId;
			var type = content.type;
			var xFieldName = content.xfieldName + '_' + content.xdisplayName;
			var yFieldName = content.yfieldName + '_' + content.ydisplayName;
			var yAxisUnit = content.yaxisUnit;
			var mapType = content.mapType;
			var staticsFieldName = '';
			if (content.staticsFieldName)
				staticsFieldName = content.staticsFieldName + '_' + content.staticsDisplayName;
			
			/**
			 * 拼装小Icon 标题 start
			 */
			var title = data.name;//data.blockIcon ? data.blockIcon + data.name : data.name;
			
			if(data.blockIcon != null && data.blockIcon != undefined && data.blockIcon != "" && data.blockIcon.indexOf("<")>0){
				title = data.blockIcon ? data.blockIcon + data.name : data.name;
			}else if(data.blockIcon != null && data.blockIcon != undefined && data.blockIcon != ""){
				$obj.find(".block-title").addClass(data.blockIcon);
				$obj.find(".block-title").css("padding-top","10px");
			} 
			
			$obj.find(".block-title").html(title);
			/**
			 * 拼装小Icon 标题 end
			 */	
			var chartObj = null;
			switch(type){
			case 1:
				chartObj = new grid({$element:$obj.find(".block-charts"),reportId:reportId});
				break;
			case 2:
				chartObj = new bar({$element:$obj.find(".block-charts"),reportId:reportId,xFieldName:xFieldName,yFieldName:yFieldName,staticsFieldName:staticsFieldName,yAxisUnit:yAxisUnit})
				break;
			case 3:
				chartObj = new line({$element:$obj.find(".block-charts"),reportId:reportId,xFieldName:xFieldName,yFieldName:yFieldName,staticsFieldName:staticsFieldName,yAxisUnit:yAxisUnit});
				break;
			case 4:
				chartObj = new pie({$element:$obj.find(".block-charts"),reportId:reportId,xFieldName:xFieldName,yFieldName:yFieldName});
				break;
			case 5:
				chartObj = new userDefined({$element:$obj.find(".block-charts"), axisType:data.contents[0].reportEchartType, url:data.contents[0].listJsonUrl});
				break;
			case 6:
				chartObj = new map({$element:$obj.find(".block-charts"),reportId:reportId,xFieldName:xFieldName,yFieldName:yFieldName,mapType:mapType});
				break;
			case 7:
				chartObj = new barAndTable({$element:$obj.find(".block-charts"),reportId:reportId,xFieldName:xFieldName,yFieldName:yFieldName,staticsFieldName:staticsFieldName,yAxisUnit:yAxisUnit})
				break;
			}
			return chartObj;
		},
		moreContent:function($obj, data) {
			var title = data.blockIcon ? data.blockIcon + data.name : data.name;
			$obj.find(".block-title").html(title);
			var chartObj = new barAndLine({$element:$obj.find(".block-charts"), blockData:data});
			return chartObj;
		},
		genSelector: function($obj,reportId,chartObj){
			var _this = this;
			$.ajax({
				 type: "POST",
				 
				 url: baseURL + "/report/simplereport/loadSelector.do",
				 data:{reportId:reportId},
				 success: function(data){
					 if(data){
						 /*var selectorData = JSON.parse(data.selectorData||"[]",function(k,v){
							  if(v.indexOf&&v.indexOf('function')>-1){
							     return eval("(function(){return "+v+" })()");
							  }
							  return v;
						 });*/
						 var selectorData = data.selectorData;
						 /*var defaultData = JSON.parse(data.defaultData||"[]",function(k,v){
							  if(v.indexOf&&v.indexOf('function')>-1){
							     return eval("(function(){return "+v+" })()");
							  }
							  return v;
						 });*/
						 var defaultData = data.defaultData;
						 /*var searchCondition = JSON.parse(data.searchCondition||"[]");*/
						 var searchCondition = data.searchCondition;
						 var selector = $.sdSelector({
							 parentElement : $obj.find(".block-search"),//父类元素
				 			 searchTab:"addPanel",
				 			 showButton:false,
				 			 showExtend:false,
				 			 searchGrid:chartObj,
				 			 selectors:selectorData	
				 		 });
				 		 selector.init();
				 		 for (var i = 0; i < searchCondition.length; i++) {
				 			 var each = searchCondition[i];
				 			 if(each.data){
				 				 selector.setSearchContainer(each.id, each.name, each.data);
				 			 }else if(each.url){
				 				_this.loadContainer(selector, each);
				 			 }
				 		 }
					 }
				 }
		 	 });
		},
		loadContainer: function(selector, each){
			$.ajax({
				 type: "POST",
				 dataType:"json",
				 url: baseURL + "/" + each.url,
				 success: function(data){
					if(data){
						selector.setSearchContainer(each.id, each.name, data);
					}
				 }
		 	 });
		}
	};
	bar = function(options){
		base = {
			$element:null,
			reportId:null,
			xFieldName:null,
			yFieldName:null,
			staticsFieldName:null,
			yAxisUnit:null,
			echart:null,
			options:{
				color:["#5ab1ef","#b6a2de","#ffb980","#97b552","#95706a","#8d98b3","#dc69aa","#e5cf0d","#91c7af","#d87a80","#2ec7c9"],
			    tooltip : {
			        trigger: 'axis',
			        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
			            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
			        }
			    },
			    grid: {
			        left: '3%',
			        right: '4%',
			        bottom: '3%',
			        containLabel: true
			    },
			    legend: {
			        data:[]
			    },
			    xAxis : [
			        {
			            type : 'category',
			            data : [],
			            axisTick: {
			                alignWithLabel: true
			            },
			            axisLine:{lineStyle:{color:"#666"}},
			            splitLine:{lineStyle:{color:"#e5e5e5"}},
			            
			        }
			    ],
			    yAxis : [
			        {
			            type : 'value',
			            axisLine:{lineStyle:{color:"#666"}},
			            splitLine:{lineStyle:{color:"#e5e5e5"}}
			        }
			    ],
			    series : []
			},
			load:function(params){
				var g = this;
				this.echart = echarts.init(this.$element[0]);
				$.ajax({
					 type: "POST",
					 
					 url: baseURL + "/report/commonreport/barReport.do?",
					 data:{reportId:this.reportId,xFieldName:this.xFieldName,yFieldName:this.yFieldName,staticsFieldName:this.staticsFieldName,params:params},
					 success: function(data){
						 data.yAxisUnit = this.yAxisUnit;
						 g.renderChartsData(data);
					 }
			 	});
			},
			renderChartsData: function(data) {
				g = this;
				if(data){
					 (g.options.xAxis[0]).data = data.xAxis;
					 g.options.legend.data = data.legend;
	                 g.options.series = data.series;
	                 if (data.yAxisUnit) {
	                 	(g.options.yAxis[0]).axisLabel = {formatter: '{value} ' + data.yAxisUnit};
	                 }
	                 this.echart.setOption(g.options,true);
				 }
			}
		}
		
		$.extend(base,options);
		return base;
	};
	pie = function(options){
		base = {
			$element:null,
			reportId:null,
			xFieldName:null,
			yFieldName:null,
			echart:null,
			options:{
				color:["#5ab1ef","#b6a2de","#ffb980","#97b552","#95706a","#8d98b3","#dc69aa","#e5cf0d","#91c7af","#d87a80","#2ec7c9"],
			    title : {
			        text: ''
			    },
			 	tooltip: {
			        trigger: 'item',
			        formatter: "{a} <br/>{b}: {c} ({d}%)"
			    },
			    /*backgroundColor: {
			        image: img1,
			        repeat: 'repeat'
			    },*/
			    legend: {
			        orient: 'vertical',
			        x: 'left',
			        itemWidth:8,
			        itemHeight:8,
			        data:[]
			    },
			    series: [{
		            name: '',
		            type: 'pie',
		            radius : '55%',
		            center: ['50%', '60%'],
		            data:[],
		            itemStyle: {
		                emphasis: {
		                    shadowBlur: 10,
		                    shadowOffsetX: 0,
		                    shadowColor: 'rgba(0, 0, 0, 0.5)'
		                }
		            }
		        }]
			},
			load:function(params){
				var g = this;
				this.echart = echarts.init(this.$element[0]);
				$.ajax({
					 type: "POST",
					 
					 url: baseURL + "/report/commonreport/pieReport.do?",
					 data:{reportId:this.reportId,xFieldName:this.xFieldName,yFieldName:this.yFieldName,params:params},
					 success: function(data){
						 g.renderChartsData(data);
					 }
			 	});
				return g;
			},
			renderChartsData: function(data) {
				g = this;
				if(data){
					 g.options.legend.data = data.legend;
	                 (g.options.series)[0].data = data.series;
	                this.echart.setOption(g.options,true);
				 }
			}
		}
		$.extend(base,options);
		return base;
	};
	line = function(options){
		base = {
			$element:null,
			reportId:null,
			xFieldName:null,
			yFieldName:null,
			staticsFieldName:null,
			yAxisUnit:null,
			echart:null,
			options:{
				color:["#5ab1ef","#b6a2de","#ffb980","#97b552","#95706a","#8d98b3","#dc69aa","#e5cf0d","#91c7af","#d87a80","#2ec7c9"],
			    title: {
			        text: ''
			    },
			    tooltip: {
			        trigger: 'axis'
			    },
			    legend: {
			        data:[]
			    },
			    grid: {
			        left: '3%',
			        right: '4%',
			        bottom: '3%',
			        containLabel: true
			    },
			    xAxis: {
			        type: 'category',
			        boundaryGap: false,
			        data: [],
			        axisLine:{lineStyle:{color:"#666"}},
		            splitLine:{lineStyle:{color:"#e5e5e5"}},
			    },
			    yAxis: {
			        type: 'value',
			        axisLine:{lineStyle:{color:"#666"}},
		            splitLine:{lineStyle:{color:"#e5e5e5"}},
			    },
			    series: []
			},
			load:function(params){
				var g = this;
				this.echart = echarts.init(this.$element[0]);
				$.ajax({
					 type: "POST",
					 
					 url: baseURL + "/report/commonreport/lineReport.do?",
					 data:{reportId:this.reportId,xFieldName:this.xFieldName,yFieldName:this.yFieldName,staticsFieldName:this.staticsFieldName,params:params},
					 success: function(data){
						 data.yAxisUnit = this.yAxisUnit;
						 g.renderChartsData(data);
					 }
			 	});
				return g;
			},
			renderChartsData: function(data) {
				g = this;
				if(data){
					 g.options.xAxis.data = data.xAxis;
					 g.options.legend.data = data.legend;
	                 g.options.series = data.series;
	                 if (data.yAxisUnit) {
	                 	g.options.yAxis.axisLabel = {formatter: '{value} ' + data.yAxisUnit};
	                 }
	                 this.echart.setOption(g.options,true);
				 }
			}
		}
		$.extend(base,options);
		return base;
	};
	grid = function(options){
		base = {
			$element:null,
			reportId:null,
			//生成列表
			genColumns : function(data){
		  	 	if(data){
		  		   var columns = new Array();
			       columns.push({field: 'number',title: '序号',formatter: function (value, row, index) {return (index+1);}});
		       
		      	   for(var key in data){
		      		   if(!data[key].isHidden){
		      			  	columns.push({title:data[key].display,field:data[key].name, type:data[key].type,align:"center" });
		      		   }
		      	    }
		      	 	return columns;
		  		}
		  	 	return null;
		    },
			initTable: function($obj,url,columns,queryParams){
				$obj.bootstrapTable({
		       		url: url,
		       		method: 'post',
		       		sidePagination: "server",
		       		dataType:'json',
		       		dataField: 'Rows',
		       		totalField: 'Total',
		       		contentType:'application/x-www-form-urlencoded',
		       		queryParamsType:"undefined",
		            striped: true,                      //是否显示行间隔色
		            pagination: true,
		       		queryParams: function(params) {
		                var param = {
	                        pageNo: params.pageNumber,
	                        perPageSize: params.pageSize,
	                        usePage: true,
	                        searchParam:queryParams
		                };
		                return param;
                    },
		            pageNumber:1,                       //初始化加载第一页，默认第一页
	                pageSize: 10,                       //每页的记录行数（*）
	                pageList: [10, 20, 50, 100],        //可供选择的每页的行数（*）
		   	        clickToSelect: true,                //是否启用点击选中行
		            uniqueId: "batchNum",                 //每一行的唯一标识，一般为主键列
		       		columns:  columns
				});
			},
			load: function(params){
				var g = this;
				$.ajax({
					 type: "POST",
					 url: baseURL + "/report/commonreport/gridReport.do?reportId="+g.reportId,
					 success: function(data){
						 if(data){
							 g.$element.empty();
							 g.$element.append('<div class="common-table"><table class="table table-hover"></table></div>');
							 var $table = g.$element.find(".table");
							 var columns = g.genColumns(data.moduleFields);
							 var url = baseURL+data.listJSONURL+'?csId='+g.reportId;
							 g.initTable($table,url,columns,params);
						 }
					 }
			 	});
			}
		}
		$.extend(base,options);
		return base;
	}
	
	barAndLine = function(options){
		base = {
			$element:null,
			blockData:null,
			echart:null,
			axisType: {'bar':2, 'line':3},
			options:{
				color:["#5ab1ef","#b6a2de","#ffb980","#97b552","#95706a","#8d98b3","#dc69aa","#e5cf0d","#91c7af","#d87a80","#2ec7c9"],
			    title: {
			        text: ''
			    },
			    tooltip: {
			        trigger: 'axis'
			    },
			    legend: {
			        data:[]
			    },
			    xAxis: [
				        {
				        	type : 'category',
				            data : [],
				            axisTick: {
				                alignWithLabel: true
				            },
				            axisLine:{lineStyle:{color:"#666"}},
				            splitLine:{lineStyle:{color:"#e5e5e5"}},
				        }
			    ],
				yAxis: [
					{
					    type : 'value',
					    axisLine:{lineStyle:{color:"#666"}},
					    splitLine:{lineStyle:{color:"#e5e5e5"}}
					},
					{
			            type : 'value',
			            axisLine:{lineStyle:{color:"#666"}},
			            splitLine:{show: false}
			        }
			    ],
			    grid: {
			        left: '3%',
			        right: '4%',
			        bottom: '3%',
			        containLabel: true
			    }
			},
			parameter: function(data) {
				var _this = this;
				if (data.contents.length == 2) {
					var param = {};
					for (var i = 0; i < data.contents.length; i++) {
						var content = data.contents[i];
						switch (content.type) {
						case _this.axisType.bar:
							param.reportId = content.reportId;
							param.xFieldName = content.xfieldName + '_' + content.xdisplayName;
							param.yBarFieldName = content.yfieldName + '_' + content.ydisplayName;
							break;
						case _this.axisType.line:
							param.yLineFieldName = content.yfieldName + '_' + content.ydisplayName;
							break;
						}
					}
					return param;
				}
				return null;
			},
			yaxisUnit: function(data) {
				var yaxisBarUnit = data.yaxisBarUnit;
				var yaxisLineUnit = data.yaxisLineUnit;
				if (yaxisBarUnit && yaxisLineUnit)
					return data;
				for (var i = 0; i < this.blockData.contents.length; i++) {
					var content = this.blockData.contents[i];
					// 2 柱形图Y轴的单位，3 折线图Y轴的单位
					if (content.type == 2 && !yaxisBarUnit) {
						yaxisBarUnit = content.yaxisUnit;
					} else if (content.type == 3 && !yaxisLineUnit) {
						yaxisLineUnit = content.yaxisUnit
					}
				}
				data.yaxisBarUnit = yaxisBarUnit;
				data.yaxisLineUnit = yaxisLineUnit;
				return data;
			},
			load: function(params){
				var _this = this;
				var data = _this.parameter(_this.blockData);
				data.params = params;
				_this.echart = echarts.init(this.$element[0]);
                 $.ajax({
					 type: "POST",
					 url: baseURL + "/report/commonreport/barAndLineReport.do?",
					 data: data,
					 dataType: 'json',
					 success: function(data){
						 _this.yaxisUnit(data);
						 _this.renderChartsData(data);
					 }
			 	});
                 return _this;
			},
			renderChartsData: function(data) {
				_this = this;
				if(data){
					 (_this.options.xAxis[0]).data = data.xAxisData;
					 (_this.options.yAxis[0]).name = data.yAxisName[0];
					 (_this.options.yAxis[1]).name = data.yAxisName[1];
					 _this.options.legend.data = data.legend;
					 _this.options.series = data.series;
					 // Y轴单位 
					 if (data.yaxisBarUnit) {
						 (_this.options.yAxis[0]).axisLabel = {formatter: '{value} ' + data.yaxisBarUnit};
					 }
					 if (data.yaxisLineUnit) {
						 (_this.options.yAxis[1]).axisLabel = {formatter: '{value} ' + data.yaxisLineUnit};
					 }
					 _this.echart.setOption(_this.options,true);
				 }
			}
		}
		$.extend(base,options);
		return base;
	}
	
	userDefined = function(options){
		base = {
			$element:null,
			axisType:null,
			url:null,
			load: function(params) {
				var g = this;
				$.ajax({
					url: baseURL + g.url,
					type: 'post',
					dataType: 'json',
					data:{params:params},
					success: function(data) {
						switch(g.axisType) {
						case 1: // 柱图
							break;
						case 2: // 折线图
							break;
						case 3: // 饼图
							break;
						case 4: // 折柱混合
							var chartObj = new barAndLine({$element:g.$element});
							chartObj.echart = echarts.init(g.$element[0]);
							chartObj.renderChartsData(data);
							break;
						}
					}
				});
				return this;
			}
		}
		$.extend(base,options);
		return base;
	}
	
	map = function(options){
		base = {
			$element:null,
			reportId:null,
			xFieldName:null,
			yFieldName:null,
			mapType:null,
			echart:null,
			options: {
    		   title: {
    	            text: '',
    	        },
    	        tooltip: {
    	            trigger: 'item'
    	        },
    	        visualMap: {
    	            min: 0,
    	            max: 300,
    	            realtime: false,
    	            calculable: true,
    	            inRange: {
    	                color: ['#14da2c','yellow', 'red']
    	            }
    	        },
    	        series: [
    	            {
    	                name: '',
    	                type: 'map',
    	                itemStyle:{
    	                    normal:{label:{show:true}},
    	                    emphasis:{label:{show:true}}
    	                }
    	            }
    	        ]
		     },
		     load: function(params){
				var _this = this;
				this.echart = echarts.init(this.$element[0]);
				$.ajax({
					 type: "POST",
					 url: baseURL + "/report/commonreport/mapReport.do",
					 data:{reportId:this.reportId,xFieldName:this.xFieldName,yFieldName:this.yFieldName,params:params},
					 success: function(data){
						 _this.renderChartsData(data);
					 }
			 	});
				return _this;
			},
			renderChartsData: function(data) {
				(this.options.series)[0].data = data.seriesData;
				this.options.visualMap.max = this.maxValue(data.seriesData);
				(this.options.series)[0].mapType = this.mapType;
				this.echart.setOption(this.options);
			},
			maxValue: function(seriesData) {
				if (seriesData && seriesData.length > 0) {
					var max = seriesData[0].value;
					for (var i = 1; i < seriesData.length; i++) {
						if (max < seriesData[i].value)
							max = seriesData[i].value;
					}
					return max;
				}
				return 200;
			}
		}
		$.extend(base,options);
		return base;
	}
	barAndTable = function(options){
		base = {
			$element:null,
			reportId:null,
			xFieldName:null,
			yFieldName:null,
			staticsFieldName:null,
			yAxisUnit:null,
			echart:null,
			options:{
				color:["#5ab1ef","#b6a2de","#ffb980","#97b552","#95706a","#8d98b3","#dc69aa","#e5cf0d","#91c7af","#d87a80","#2ec7c9"],
			    tooltip : {
			        trigger: 'axis',
			        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
			            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
			        }
			    },
			    grid: {
			    	left: '3%',
			        right: '4%',
			        bottom: '50%',
			        containLabel: true
			    },
			    legend: {
			        data:[]
			    },
			    xAxis : [
			        {
			            type : 'category',
			            data : [],
			            axisTick: {
			                alignWithLabel: true
			            },
			            axisLine:{lineStyle:{color:"#666"}},
			            splitLine:{lineStyle:{color:"#e5e5e5"}},
			            
			        }
			    ],
			    yAxis : [
			        {
			            type : 'value',
			            axisLine:{lineStyle:{color:"#666"}},
			            splitLine:{lineStyle:{color:"#e5e5e5"}}
			        }
			    ],
			    series : []
			},
			load:function(params){
				var g = this;
				this.echart = echarts.init(this.$element[0]);
				$.ajax({
					 type: "POST",
					 
					 url: baseURL + "/report/commonreport/barReport.do?",
					 data:{reportId:this.reportId,xFieldName:this.xFieldName,yFieldName:this.yFieldName,staticsFieldName:this.staticsFieldName,params:params},
					 success: function(data){
						 data.yAxisUnit = this.yAxisUnit;
						 g.renderChartsData(data);
						 
						 var content='<table class="table table-bordered  table-hover  table-striped" style="width:700px;margin:-420px 4%;text-align:center">'
						 +'<tr><td></td>';
						 for(var i=0;i<data.xAxis.length;i++){
							 content+='<td>'+data.xAxis[i]+'</td>';
						 }
						 +'</tr>';
						 for(var i=0;i<data.series.length;i++){
							 content+='<tr>';
							 content+='<td>'+data.series[i].name+'</td>';
							 for(var j=0;j<data.series[i].data.length;j++){
								 content+='<td>'+data.series[i].data[j]+'</td>';
							 }
							 content+='</tr>';
						 }
						 content+='</table>';
						 options.$element.append(content);
					 }
			 	});
			},
			renderChartsData: function(data) {
				g = this;
				if(data){
					 (g.options.xAxis[0]).data = data.xAxis;
					 g.options.legend.data = data.legend;
	                 g.options.series = data.series;
	                 if (data.yAxisUnit) {
	                 	(g.options.yAxis[0]).axisLabel = {formatter: '{value} ' + data.yAxisUnit};
	                 }
	                 this.echart.setOption(g.options,true);
				 }
			}
		}
		
		$.extend(base,options);
		return base;
	};
})(jQuery);